var websocket = null;

//150811 gzf 选择设备后才连接socket
//$(function(){
//	//登录了才连接
//	$.get("isLogin.action",
//			{},
//			function(response){
//				if(response.result == "success") {
//					var guid = getGuid(); 
//					websocket_init(guid);
//				}
//				else alert("cannot connect");
//			},
//			"json"
//	);
//});

function websocket_init(guid){
	//判断当前浏览器是否支持WebSocket
    if('WebSocket' in window){
    	var host = window.location.host;
    	var url = "ws://" + host + "/sgwebsocket/" + guid;
        websocket = new WebSocket(url);
        alert("哈哈，我连上了");
    }
    else{
        alert('Not support websocket')
    }
    
    //连接发生错误的回调方法
    websocket.onerror = function(){
//        alert("websocket failed");
    };
     
    //连接成功建立的回调方法
    websocket.onopen = function(event){
        //alert("websocket open");
        //$("#test").removeAttr("disabled");
    }
     
    //接收到消息的回调方法
    websocket.onmessage = function(){
        //alert(event.data);
        messagehandler(event.data);
    }
     
    //连接关闭的回调方法
    websocket.onclose = function(){
    	// TODO 主动让服务器端删除socket的session
        alert("websocket close");
        self.location="/";
    }
     
    //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
    window.onbeforeunload = function(){
        websocket.close();
        alert("onbeforeunload");
    }
}

function websocket_getSocket(){
	if(websocket != null) return websocket;
	else alert("websocket未初始化");
}

function websocket_send(msg){
	if(websocket != null) {
		websocket.send(msg);
	}
	//else alert("websocket未初始化");
}

function test(){
	websocket_send("hello");
}
